//
//  PTHandler.m
//  pintu
//
//  Created by Fxxx on 2017/11/29.
//  Copyright © 2017年 lu. All rights reserved.
//

#import "PTHandler.h"

@interface PTHandler ()

@property (weak ,nonatomic ,readonly) id<PTHandlerDelegate> delegate;
@property (assign ,nonatomic ,readonly) NSInteger space; // 空格区域
@end

@implementation PTHandler

- (PTHandler *)initWithImage:(UIImage *)image
                       level:(PTLevel)level
                    delegate:(id<PTHandlerDelegate>)delegate; {
    self = [super init];
    if (self) {
        _level = level;
        _delegate = delegate;
        
        // 初始化索引
        {
            /**
             0   1   2
             3   4   5
             6   7   space
             */
            NSMutableArray *array = [NSMutableArray array];
            NSInteger count = _level * _level;
            for (int i = 0; i < count; i ++) {
                [array addObject:@(i)];
            }
            _indexes = array.copy;
            _space = _indexes.lastObject.integerValue;
        }
        
        // 处理图片
        {
            _image = image;
            if (_image.size.width != _image.size.height) {
                CGRect rect = {};
                rect.size.width = MIN(_image.size.width, _image.size.height);
                rect.size.height = rect.size.width;
                CGFloat ox = (_image.size.width - _image.size.height) * .5;
                if (ox > 0) {
                    rect.origin.x = ox; rect.origin.y = 0;
                } else {
                    rect.origin.x = 0; rect.origin.y = fabs(ox);
                }
                _image = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(_image.CGImage, rect)];
            }
        }
        
        // 分割图片
        {
            NSMutableArray *images = [NSMutableArray arrayWithCapacity:_indexes.count];
            CGFloat width = _image.size.width / (float)_level;
            for (int i = 0; i < _indexes.count; i ++) {
                if (i == _space) {
                    [images addObject:[NSNull null]];
                } else {
                    CGRect rect = CGRectMake(i % _level * width, i / _level * width, width, width);
                    UIImage *insert = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(_image.CGImage, rect)];
                    if (insert) [images addObject:insert];
                }
            }
            _images = images.copy;
        }
    } return self;
}

- (void)upset; {
    NSInteger upsetcount = arc4random() % 300 + 100;
    for (int i = 0; i < upsetcount; i ++) {
        NSMutableArray *canmoveindex = [NSMutableArray array];
        for (int ci = 0; ci < _indexes.count; ci ++) {
            if ([self canmove:ci]) {
                [canmoveindex addObject:@(ci)];
            }
        }
        // 随机打乱一格
        NSInteger moveindex = [canmoveindex[arc4random() % canmoveindex.count] integerValue];
        [self update:moveindex delegateComplet:NO];
    }
    
    if (_delegate) {
        [_delegate handlerImages:_images didChangeIndexes:_indexes];
    }
}

- (void)update:(NSInteger)index {
    [self update:index delegateComplet:YES];
}

/**
 @param index 点击的格子
 @param delegateComplet 是否通知代理回调
 */
- (void)update:(NSInteger)index delegateComplet:(BOOL)delegateComplet {
    if ([self canmove:index]) {
        
        NSInteger spaceindex = 0;
        for (int i = 0; i < _indexes.count; i ++) {
            if (_indexes[i].integerValue == _space) {
                spaceindex = i; break;
            }
        }
        NSNumber *clickValue = _indexes[index];
        
        // 交换点击格与空格的位置
        NSMutableArray *array = _indexes.mutableCopy;
        array[index] = @(_space);
        array[spaceindex] = clickValue;
        _indexes = array.copy;
        
        if (delegateComplet) {
            if (_delegate) {
                [_delegate handlerImages:_images didChangeIndexes:_indexes];
            }
        }
    }
}

- (BOOL)canmove:(NSInteger)index {
    BOOL canmove = NO;
    
    // 上
    if (!canmove) {
        if (index - _level >= 0) {
            NSInteger toindex = index - _level;
            if (_indexes[toindex].integerValue == _space) {
                canmove = YES;
            }
        }
    }
    
    // 下
    if (!canmove) {
        if (index + _level < _indexes.count) {
            NSInteger toindex = index + _level;
            if (_indexes[toindex].integerValue == _space) {
                canmove = YES;
            }
        }
    }
    
    // 左
    if (!canmove) {
        if (index % _level > 0) {
            NSInteger toindex = index - 1;
            if (toindex >= 0) {
                if (_indexes[toindex].integerValue == _space) {
                    canmove = YES;
                }
            }
        }
    }
    
    // 右
    if (!canmove) {
        if (index % _level < (_level - 1)) {
            NSInteger toindex = index + 1;
            if (toindex < _indexes.count) {
                if (_indexes[toindex].integerValue == _space) {
                    canmove = YES;
                }
            }
        }
    }
    return canmove;
}

@end
